package com.turman.math_learn

import android.annotation.SuppressLint
import android.app.Activity
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.annotation.RequiresApi
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Scaffold
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.viewinterop.AndroidView
import androidx.core.view.WindowCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.WindowInsetsControllerCompat
import com.tencent.smtt.export.external.interfaces.ConsoleMessage
import com.tencent.smtt.export.external.interfaces.WebResourceError
import com.tencent.smtt.export.external.interfaces.WebResourceRequest
import com.tencent.smtt.sdk.WebChromeClient
import com.tencent.smtt.sdk.WebView
import com.tencent.smtt.sdk.WebViewClient
import com.turman.math_learn.ui.theme.MathlearnTheme
import java.io.IOException

class MainActivity : ComponentActivity() {
    private var localWebServer: LocalWebServer? = null

    @RequiresApi(Build.VERSION_CODES.O)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        // 启动本地服务器
        localWebServer = LocalWebServer(this, 8080)
        try {
            localWebServer?.start()
        } catch (e: IOException) {
            Log.e("LocalServer", "Failed to start server", e)
        }

        // 全屏和沉浸式配置
        WindowCompat.setDecorFitsSystemWindows(window, false)
        WindowInsetsControllerCompat(window, window.decorView).apply {
            hide(WindowInsetsCompat.Type.statusBars() or WindowInsetsCompat.Type.navigationBars())
            systemBarsBehavior = WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE
        }

        enableEdgeToEdge()
        setContent {
            MathlearnTheme {
                Scaffold(modifier = Modifier.fillMaxSize()) { innerPadding ->
                    WebPage(
                        url = "http://localhost:8080",
                        modifier = Modifier.fillMaxSize().padding(innerPadding),
                        activity = this
                    )
                }
            }
        }
    }

    override fun onDestroy() {
        localWebServer?.stop()
        super.onDestroy()
    }
}

@SuppressLint("SetJavaScriptEnabled")
@Composable
fun WebPage(url: String, modifier: Modifier = Modifier, activity: Activity) {
    AndroidView(
        factory = { context ->
            WebView(context).apply {
                // 启用 JavaScript 和 WebGL
                settings.javaScriptEnabled = true
                settings.domStorageEnabled = true
                settings.useWideViewPort = true
                settings.loadWithOverviewMode = true
                settings.domStorageEnabled = true
                settings.setSupportZoom(false)

                // 强制 WebView 使用硬件加速（对 WebGL 至关重要）
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                    setLayerType(View.LAYER_TYPE_HARDWARE, null)
                }
                settings.setSupportZoom(false)
                settings.builtInZoomControls = false
                settings.displayZoomControls = false

                // 启用硬件加速（对 WebGL 性能至关重要）
                setLayerType(View.LAYER_TYPE_HARDWARE, null)

                // 调试 WebGL 问题
                WebView.setWebContentsDebuggingEnabled(true)

                webViewClient = object : WebViewClient() {
                    override fun onReceivedError(
                        view: WebView,
                        request: WebResourceRequest,
                        error: WebResourceError
                    ) {
                        Log.e("WebView", "Error loading URL: ${error.description}")
                    }

                    override fun onPageFinished(view: WebView?, url: String?) {
                        super.onPageFinished(view, url)
                        Log.d("WebView", "Page loaded: $url")
                        // 可以在这里检查 WebGL 是否可用
                        evaluateJavascript(
                            "typeof WebGLRenderingContext !== 'undefined'",
                            { result ->
                                Log.d("WebView", "WebGL supported: $result")
                            }
                        )
                        evaluateJavascript("""
                            if (typeof window.onWebViewResize === 'function') {
                                window.onWebViewResize();
                            }
                        """, null)
                    }
                }

                webChromeClient = object : WebChromeClient() {
                    override fun onConsoleMessage(consoleMessage: ConsoleMessage): Boolean {
                        Log.d("WebView", "${consoleMessage.message()} -- line ${consoleMessage.lineNumber()}")
                        return true
                    }
                }
            }
        },
        modifier = modifier,
        update = { webView ->
            webView.loadUrl(url)
        }
    )
}